package com.hollowlatte.common.exceptionhandler;

import com.hollowlatte.common.utils.Result;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Hollow Latte
 * @date 2021/4/26 15:47
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result error(Exception e) {
        e.printStackTrace();
        return Result.error("B0001", "系统执行出错");
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result error(CustomException e) {
        e.printStackTrace();
        return Result.error(e.getCode(), e.getMessage());
    }


    // 权限相关异常

    /**
     * 抛出以指示请求的操作或对请求的资源的访问是不允许的
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public Result error(UnauthorizedException e) {
        e.printStackTrace();
        return Result.error("A0301", "访问未授权");
    }

    /**
     * 当尚未完成成功认证时，尝试执行授权操作时引发异常
     */
    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseBody
    public Result error(UnauthenticatedException e) {
        e.printStackTrace();
        return Result.error("A0312", "无权使用API");
    }

    // 登录相关异常

    @ExceptionHandler(UnknownAccountException.class)
    @ResponseBody
    public Result error(UnknownAccountException e) {
        e.printStackTrace();
        return Result.error("A0201", "用户账户不存在");
    }

    @ExceptionHandler(IncorrectCredentialsException.class)
    @ResponseBody
    public Result error(IncorrectCredentialsException e) {
        e.printStackTrace();
        return Result.error("A0210", "用户密码错误");
    }
}
